#include "game.h"

mutex mutex_keyboard[2];
mutex mutex_pos;

game::game()
{
	p1 = player(0, 0, 0, &keyboard[0], &positionQueue);
	p2 = player(7, 7, 1, &keyboard[1], &positionQueue);
	p1pos = pos(0, 0, 0);
	p2pos = pos(7, 7, 1);
	for (int i = 0; i < 8; i++)
	{
		for (int j = 0; j < 8; j++)
		{
			board[i][j] = '_';
		}
	}
	board[p1pos.x][p1pos.y] = '1';
	board[p2pos.x][p2pos.y] = '2';
}


game::~game()
{
}

void game::run()
{
	bool playing = true;
	updatepos = true;

	thread t1(p1), t2(p2);

	while (playing)
	{			
		input();
		this_thread::sleep_for(chrono::milliseconds(1));
		
		if (updatepos)
		{
			updatePos();
			draw();			
		}			
	}
}

void game::input()
{
	if (_kbhit())
	{
		char input = _getch();
		updatepos = true;
		
		switch (input)
		{
		case 'w':
		case 'a':
		case 's':
		case 'd':
			mutex_keyboard[0].lock();
			keyboard[0].push_back(input);
			mutex_keyboard[0].unlock();
			break;
		case 'i':
			mutex_keyboard[1].lock();
			keyboard[1].push_back('w');
			mutex_keyboard[1].unlock();
			break;
		case 'j':
			mutex_keyboard[1].lock();
			keyboard[1].push_back('a');
			mutex_keyboard[1].unlock();
			break;
		case 'k':
			mutex_keyboard[1].lock();
			keyboard[1].push_back('s');
			mutex_keyboard[1].unlock();
			break;
		case 'l':
			mutex_keyboard[1].lock();
			keyboard[1].push_back('d');
			mutex_keyboard[1].unlock();
			break;
		}
	}		
}

void game::updatePos()
{
	mutex_pos.lock();
	while (!positionQueue.empty())
	{
		pos temp = positionQueue.front();
		if (temp.playerid == 0)
		{
			board[p1pos.x][p1pos.y] = '_';
			board[temp.x][temp.y] = '1';
			p1pos = temp;
		}
		else
		{
			board[p2pos.x][p2pos.y] = '_';
			board[temp.x][temp.y] = '2';
			p2pos = temp;
		}
		positionQueue.pop_front();		
	}
	mutex_pos.unlock();
}

void game::draw()
{
	system("cls");	
	for (int i = 0; i < 8; i++)
	{
		for (int j = 0; j < 8; j++)
		{
			cout << board[j][i];
		}
		cout << endl;
	}
	updatepos = false;
}